﻿using System;
using System.Configuration;
using System.Drawing;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Xml;
using System.IO;
using Srvtools;
using Microsoft.Win32;

namespace EEPNetFLClient
{
	/// <summary>
	/// Summary description for WinForm1.
	/// </summary>
	public partial class frmLogin : System.Windows.Forms.Form
    {
        private Panel panel1;
        private ComboBox edtSol;
        private ComboBox edtDB;
        private ComboBox edtUserId;
        private Label label3;
        private Label lblDB;
        private TextBox edtPwd;
        private Button button2;
        private Button button1;
        private Label label2;
        private Label label1;
        private Label label4;
        private Button btnConfig;
        private GroupBox grpClient;
        private GroupBox grpServer;
        private TextBox txtServerPort;
        private Label label6;
        private TextBox txtLoginPort;
        private Label label5;
        private Label label8;
        private Button btnReset;
        private Button btnSave;
        private Button btnRefresh;
        private ComboBox cmbLogin;
        private ComboBox cmbServer;
        private Ascend.Windows.Forms.GradientPanel gradientPanel1;
        private PictureBox pictureBox1;
        
		public string GetUserId()
		{
			return edtUserId.Text.Trim();
        }
		public string GetPwd()
		{
            return edtPwd.Text.Trim();
		}
		public string GetDB()
		{
            return edtDB.Text.Trim();
		}
        public string GetCurProject()
        {
            return edtSol.SelectedValue.ToString().Trim();
        }
        private bool register = false;
		public frmLogin(bool reg)
		{
			InitializeComponent();
            register = reg;
            InitForm();
		}

        private void InitForm()
        {
            string picPath = "";
            picPath = Application.StartupPath + "\\Config\\login.png";
            if (File.Exists(picPath))
            {
                this.pictureBox1.Image = Image.FromFile(picPath);
            }                        
        }
		
        private void WinForm1_Load(object sender, System.EventArgs e)
        {            
            if (register)
            {
                string[] caption = SysMsg.GetSystemMessage(CliUtils.fClientLang, "EEPWebNetClient", "WinSysMsg", "txt_Login").Split(';');
                label1.Text = caption[0];
                label2.Text = caption[1];
                label3.Text = caption[3];
                lblDB.Text = caption[2];
            }
            String s = Application.StartupPath + "\\EEPNetClient.xml";
            string sUser = "";
            string sDB = "";
            string sSol = "";
            if (File.Exists(s))
            {
                XmlDocument xml = new XmlDocument();
                xml.Load(s);
                XmlNode el = xml.DocumentElement;
                foreach (XmlNode xNode in el.ChildNodes)
                {

                    if (xNode.Name.ToUpper().Equals("USER"))
                    {
                        sUser = xNode.InnerText.Trim();
                    }
                    else if (xNode.Name.ToUpper().Equals("DATABASE"))
                    {
                        sDB = xNode.InnerText.Trim();
                    }
                    else if (xNode.Name.ToUpper().Equals("SOLUTION"))
                    {
                        sSol = xNode.InnerText.Trim();
                    }
                }
            }            
            if (edtUserId.Items.Count == 0)
            {
                if (sUser != "")
                {
                    string[] sUsers = sUser.Split(new char[] { ',' });
                    edtUserId.Items.AddRange(sUsers);
                    edtUserId.SelectedIndex = 0;
                }
                else
                {
                 //   edtUserId.Text = "001";
                }
            }

            if (register)
            {
                if (edtDB.Items.Count == 0)
                {
                    object[] myRet1 = CliUtils.CallMethod("GLModule", "GetDB", null);
                    if (myRet1[1] != null && myRet1[1] is ArrayList)
                    {
                        ArrayList dbList = (ArrayList)myRet1[1];
                        foreach (string db in dbList)
                        {
                            this.edtDB.Items.Add(db);
                        }
                    }
                    string[] sDBs = sDB.Split(',');
                    if (sDBs[0] != "" && this.edtDB.Items.Contains(sDBs[0]))
                    {
                        this.edtDB.SelectedItem = sDBs[0];
                    }
                    else if (edtDB.Items.Count > 0)
                    {
                        edtDB.SelectedIndex = 0;
                    }
                }
                if (edtDB.SelectedItem != null)
                {
                    loadSysSolutions();
                    string[] sSols = sSol.Split(',');
                    if (sSols[0] != "")
                    {
                        foreach (DataRowView row in this.edtSol.Items)
                        {
                            if (row["itemtype"].ToString() == sSols[0])
                            {
                                this.edtSol.SelectedItem = row;
                                break;
                            }
                        }
                    }
                    else if (edtSol.Items.Count > 0)
                    {
                        edtSol.SelectedIndex = 0;
                    }
                }                 
            }
            try
            {
                ReadConfig();
                this.btnSave.Enabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

          
        }

        private void loadSysSolutions()
        {
            object[] objParam = new object[1];
            objParam[0] = this.edtDB.SelectedItem.ToString();
            DataSet dsSolution = new DataSet();
            object[] myRet1 = CliUtils.CallMethod("GLModule", "GetSolution", objParam);
            if ((null != myRet1) && (0 == (int)myRet1[0]))
                dsSolution = ((DataSet)myRet1[1]);
            edtSol.DataSource = dsSolution.Tables[0];
            edtSol.DisplayMember = "itemname";
            edtSol.ValueMember = "itemtype";

        }

        bool _Expand = false;
        private void btnConfig_Click(object sender, EventArgs e)
        {
            if (!_Expand)
            {
                this.Height = 510;
                _Expand = true;
                (sender as Button).Text = "选项(&O)<<";
            }
            else
            {
                this.Height = 274;
                _Expand = false;
                (sender as Button).Text = "选项(&O)>>";
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (!BeforeSaveConfig())
                    return;
                WriteConfig();                
                Application.Exit();
                System.Diagnostics.Process.Start("EEPNetFLClient.exe");
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存配置文件出错:\r\n\r\n"+ex.Message,"错误提示",MessageBoxButtons.OK ,MessageBoxIcon.Error);
            }
        }

        private bool BeforeSaveConfig()
        {            
            string _str;
            _str= this.cmbLogin.Text;
            if (_str.Split('.').Length != 4)
                throw new Exception("IP地址格式不对");                
            foreach (string _s in _str.Split('.'))
            {
                if (!IsNumber(_s,"IP"))
                    throw new Exception("IP地址格式不对,每段数字应介于0 到 255");                
            }
            _str = this.cmbServer.Text;
            if (_str.Split('.').Length != 4)            
                throw new Exception("IP地址格式不对");                         
            foreach (string _s in _str.Split('.'))
            {
                if (!IsNumber(_s, "IP"))
                    throw new Exception("IP地址格式不对,每段数字应介于0 到 255");            
            }           
            if (!IsNumber(this.txtLoginPort.Text,"PORT"))
                throw new Exception("端口格式不对,数字应介于1 到 65535");           
            if (!IsNumber(this.txtServerPort.Text, "PORT"))
                throw new Exception("端口格式不对,数字应介于1 到 65535");           
            return true;
        }

        private bool IsNumber(string s,string flag)
        {
            int i;
            if (!int.TryParse(s, out i))
                return false;
            if (flag.ToUpper() == "IP")
                if (i < 0 || i > 255)
                    return false;
            if (flag.ToUpper() == "PORT")
                if (i < 1 || i > 65535)
                    return false;
            return true;
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            string _serverIp = System.Configuration.ConfigurationManager.AppSettings["ServerIp"];
            this.cmbLogin.Items.Clear();
            this.cmbLogin.Items.Add(_serverIp);
            this.cmbLogin.SelectedIndex = 0;

            this.cmbServer.Items.Clear();
            this.cmbServer.Items.Add(_serverIp);
            this.cmbServer.SelectedIndex = 0;
            
            this.txtLoginPort.Text = "8989";
            this.txtServerPort.Text = "8000";
                   
            this.btnSave.Enabled = true;
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(Application.ExecutablePath + ".config");
            XmlNode xNode;
            XmlElement xElem;
            xNode = xDoc.SelectSingleNode("//appSettings");
            xElem = (XmlElement)xNode.SelectSingleNode("//add[@key=\"SvrsLogin\"]");
            if (xElem != null )
            {                
                xElem.SetAttribute("value", "");
            }            
            xElem = (XmlElement)xNode.SelectSingleNode("//add[@key=\"SvrsApp\"]");
            if (xElem != null)
            {
                xElem.SetAttribute("value", "");
            }                        
            xElem = (XmlElement)xNode.SelectSingleNode("//add[@key=\"SvrsUpdater\"]");
            if (xElem != null)
            {
                xElem.SetAttribute("value", "");
            }                        
            xDoc.Save(Application.ExecutablePath + ".config");                    
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            this.cmbLogin.Items.Clear();
            this.cmbServer.Items.Clear();            
            ReadConfig();
            this.btnSave.Enabled = false;
        }
     
        private void ReadConfig()
        {
            this.cmbLogin.Items.Clear();
            this.cmbServer.Items.Clear();
            
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(Application.ExecutablePath+".config");
            XmlNode xNode;
            XmlElement xElem;            
            string _strs = "";
            string _sLogin = "";
            string _sApp = "";            
            xNode = xDoc.SelectSingleNode("//system.runtime.remoting/application/client");
            xElem = (XmlElement)xNode.SelectSingleNode("//wellknown[@type=\"Srvtools.LoginService, Srvtools\"]");
            if (xElem != null)
            {
                _strs = xElem.GetAttribute("url");
                _sLogin = _strs.Split(':')[1].Split(("//").ToCharArray())[2];
                this.txtLoginPort.Text = _strs.Split(':')[2].Split('/')[0];
            }
            xElem = (XmlElement)xNode.SelectSingleNode("//wellknown[@type=\"Srvtools.ListenerService, Srvtools\"]");
            if (xElem != null)
            {
                _strs = xElem.GetAttribute("url");
                _sApp = _strs.Split(':')[1].Split(("//").ToCharArray())[2];
                this.txtServerPort.Text = _strs.Split(':')[2].Split('/')[0];
            }
            xNode = xDoc.SelectSingleNode("//appSettings");
            string _serverIp = System.Configuration.ConfigurationManager.AppSettings["ServerIp"];

            _strs = "";
            xElem = (XmlElement)xNode.SelectSingleNode("//add[@key=\"Servers\"]");
            if (xElem != null)
                _strs = xElem.GetAttribute("value");
            if (_strs == "") _strs = _serverIp;
            foreach (string _s in _strs.Split(';'))
            {
                if (_s.Trim() != "")
                {
                    this.cmbLogin.Items.Add(_s);      
                    this.cmbServer.Items.Add(_s);
                }
            }
            if (this.cmbLogin.Items.IndexOf(_sLogin) == -1)
                this.cmbLogin.Items.Add(_sLogin);
            this.cmbLogin.SelectedIndex = this.cmbLogin.Items.IndexOf(_sLogin);

            if (this.cmbServer.Items.IndexOf(_sApp) == -1)
                this.cmbServer.Items.Add(_sApp);
            this.cmbServer.SelectedIndex = this.cmbServer.Items.IndexOf(_sApp);            
        }

        private void WriteConfig()
        {            
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(Application.ExecutablePath + ".config");
            XmlNode xNode;
            XmlElement xElem;            
            xNode = xDoc.SelectSingleNode("//system.runtime.remoting/application/client");
            xElem = (XmlElement)xNode.SelectSingleNode("//wellknown[@type=\"Srvtools.LoginService, Srvtools\"]");
            if (xElem != null)
                xElem.SetAttribute("url", String.Format("http://{0}:{1}/Srvtools.rem", this.cmbLogin.Text.Trim(), this.txtLoginPort.Text.Trim()));
            xElem = (XmlElement)xNode.SelectSingleNode("//wellknown[@type=\"Srvtools.ListenerService, Srvtools\"]");
            if (xElem != null)
                xElem.SetAttribute("url", String.Format("http://{0}:{1}/Srvtools.rem", this.cmbServer.Text.Trim(), this.txtServerPort.Text.Trim()));

            xNode = xDoc.SelectSingleNode("//appSettings");           
            
            string _strs = "";
            string _s = "";
            _s = this.cmbLogin.Text;
            xElem = (XmlElement)xNode.SelectSingleNode("//add[@key=\"Servers\"]");
            if (xElem != null && _s!="")
            {
                _strs = xElem.GetAttribute("value");
                if ((";" + _strs + ";").IndexOf(";" + _s + ";") == -1)
                    _strs = _strs + ";" + _s;
                xElem.SetAttribute("value", _strs);
            }
            
            xDoc.Save(Application.ExecutablePath + ".config");                      
        }

        private void cmbLogin_TextChanged(object sender, EventArgs e)
        {
            this.btnSave.Enabled = true;
        }

        private void frmLogin_Activated(object sender, EventArgs e)
        {
            SetForegroundWindow(this.Handle);
            frmWaiting.CloseWaiting();            
            this.edtPwd.SelectAll();         
        }

        [System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);

        private void frmLogin_Enter(object sender, EventArgs e)
        {
            edtPwd.Focus();
        }//设置此窗体句柄的窗体为活动窗体
    }
}
                                                                